/**************************************************************************//**
 * @file    UtunitsHelper.c
 * @author  İsmail SEZEN (email: sezenismail@gmail.com)
 * @date    02-08-2010
 *
 * @note This is part of siklon project. (Siklon.c)
 *
 * <b>Description</b>
 *
 * Includes helper routines to manipulate the unit conversions.\n
 *
 * Copyright (C) 2009 İsmail SEZEN
 *
 * <b>License</b>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/

/**Include Drectives*///{
#include <stdio.h>
#include<udunits.h>
//}

/**Variables*///{
utUnit* unit = NULL;
//}

/**Function: start_udunits
* Starts the udunits*/
int start_udunits() {
	///http://www.unidata.ucar.edu/software/netcdf/time/0052.html
	///http://www.unidata.ucar.edu/cgi-bin/man-cgi?udunits+-s3
	///http://www.unidata.ucar.edu/software/udunits/udunits-1/index.html
	ut_set_error_message_handler(ut_ignore);
	int result = utInit(NULL);
	ut_set_error_message_handler(ut_write_to_stderr);
	 return result;
}

int udunits_start_scan(char* attr, utUnit* unit) {
	int result = 0;
	 if ((result = start_udunits()) == 0) {
		 result = utScan(attr, unit);
	 }
	 return result;
}

int udunits_scan(char* attr) {
	return udunits_start_scan(attr,unit);
}

void print_time(double* val,utUnit* unit){
	char string[256];
	int year,month,day,hour,minute;
	float second;
	utCalendar(*val, unit, &year, &month, &day, &hour,&minute, &second);
	//sprintf(string, "%d-%d-%d %d:%d:%d", year, month,day, hour, minute, (int)second);
	sprintf(string, "%d;%02d;%02d;%02d", year, month,day, hour);
	printf("%8s",string);
}

int print_converted_times(char* attr,double *times,int length) {
	int result = 0;
	utUnit  unit;
	if ((result = udunits_start_scan(attr,&unit)) == 0) {
		printf("TimesLength: %d (%d TO %d) \n",length,0,length-1);
		printf("time :\n");
		int cnt = 0,i = 0;
		for(i =0 ;i < length;i++){
			print_time(&times[i],&unit);
			if(cnt == 6) {printf("\n");cnt = -1;}
			cnt++;
		}
	}
	return result;
}

int convert_time(double* val,int* year,int* month,int* day,int* hour,int* minute,float* second) {
	int result = 0;
	if(unit !=NULL) {
		result = utCalendar(*val, unit, year, month, day, hour, minute, second);
	}
	return result;
}
